package com.centit.airplanebaseinfo.po;


import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpsPost {

    //public static final BaseBean bb = new BaseBean();

    /**
     * 只信任特定机构颁发的证书
     * 安全,域名校验,建议使用
     *
     * @return
     */
    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

    public static String sendPost(String url, Map<String, String> paraMap) {
        String responseBody = "";
        AtomicInteger status = new AtomicInteger(-1);
        CloseableHttpClient httpClient = null;
        System.out.println("请求目标：url = " + url);

        List<NameValuePair> params = new ArrayList<>();
        try {
            if (url.startsWith("https")) {
                System.out.println("https请求");
                httpClient = createSSLClientDefault();
            } else {
                System.out.println("http请求");
                httpClient = HttpClients.createDefault();
            }

            HttpPost httpPost = new HttpPost(url);
            if (paraMap != null && paraMap.size() != 0) {
                for (Map.Entry<String, String> entry : paraMap.entrySet()) {
                    params.add(new NameValuePair() {
                        @Override
                        public String getName() {
                            return entry.getKey();
                        }
                        @Override
                        public String getValue() {
                            return entry.getValue();
                        }
                    });
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, "GBK"));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");

            responseBody = httpClient.execute(httpPost, httpResponse -> {
                status.set(httpResponse.getStatusLine().getStatusCode());
                HttpEntity entity = httpResponse.getEntity();
                System.out.println("----返回值---"+ JSON.toJSONString(entity));
                return entity != null ? EntityUtils.toString(entity,"GBK") : null;
            });

            responseBody = replaceBlank(responseBody);
            System.out.println("responseBody11111 = " + responseBody);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("e1:" + e);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            System.out.println("e2:" + e);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("e3:" + e);
        } finally {
            try {  //关闭连接、释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseBody;

    }

    public static JSONObject sendGET(String url) {
        JSONObject object = new JSONObject();
        CloseableHttpClient httpClient = null;
        try {
            if (url.startsWith("https")) {
                System.out.println("https请求");
                httpClient = createSSLClientDefault();
            } else {
                System.out.println("http请求");
                httpClient = HttpClients.createDefault();
            }

            AtomicInteger status = new AtomicInteger(-1);
            HttpGet httpGet = new HttpGet(url);
            String responseBody = httpClient.execute(httpGet, httpResponse -> {
                status.set(httpResponse.getStatusLine().getStatusCode());
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            });
            responseBody = replaceBlank(responseBody);
            System.out.println("responseBody = " + responseBody);
            object.put("responseBody", responseBody);
            object.put("status", status);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("e1:" + e);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            System.out.println("e2:" + e);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("e3:" + e);
        } finally {
            try {  //关闭连接、释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("object = " + object);
        return object;
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

}
